package com.bytech.admin.biz.controller;

import java.util.Arrays;
import java.util.Optional;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bytech.common.biz.entity.blogUser.BlogUserAgent;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bytech.admin.biz.annotation.NoAdminCheck;
import com.bytech.common.biz.entity.blogUser.BlogUser;
import com.bytech.common.biz.entity.blogUser.BlogUserLoginDto;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.service.remote.user.RemoteBlogUserService;
import com.bytech.common.config.AppGlobalConstants;

/**
 * @Author Zhao
 * @Create 2021/8/9 14:40
 */
@Controller
public class LoginOutController {

    @Resource
    private RemoteBlogUserService remoteBlogUserService;

    @GetMapping("/login")
    @NoAdminCheck
    public String toLogin() {
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public BaseResult<BlogUser> doLogin(BlogUserLoginDto loginDto, HttpServletRequest request, HttpServletResponse response) {
        loginDto.setLoginIp(request.getRemoteAddr());
        BaseResult<BlogUser> loginResult = remoteBlogUserService.doLogin(loginDto);
        if (!loginResult.isSuccess()) {
            return loginResult;
        }
        BlogUser user = loginResult.getData();
        // 保持会话
        HttpSession session = request.getSession();
        session.setAttribute(AppGlobalConstants.BLOG_USER_SESSION_KEY, new BlogUserAgent(user));
        session.setMaxInactiveInterval(AppGlobalConstants.BLOG_USER_SESSION_EXPIRED);
        boolean rememberLogin = loginDto.getRememberMe() != null && loginDto.getRememberMe();
        if (rememberLogin) {
            Optional<Cookie> opCookie = Arrays.stream(request.getCookies()).filter(e -> e.getName().equals(AppGlobalConstants.BLOG_USER_COOKIE_KEY)).findFirst();
            if (!opCookie.isPresent()) {
                // 记住登录状态
                Cookie cookie = new Cookie(AppGlobalConstants.BLOG_USER_COOKIE_KEY, user.getToken());
                cookie.setMaxAge(AppGlobalConstants.BLOG_USER_COOKIE_EXPIRED);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
        return BaseResult.<BlogUser>success("登录成功").data(null).build();
    }
}
